import React from 'react'
import { useSelector } from 'react-redux'
import type { RootState } from '../store/store'

interface Props extends React.ButtonHTMLAttributes<HTMLButtonElement> {
    allowRoles?: Array<'admin' | 'user'>
    deny?: boolean // if true, hide instead of disable
}

export default function AuthButton({
    allowRoles = ['admin'],  //默认允许admin角色
    deny = false,  // 是否隐藏
    children,
    ...rest }: Props) {
    //从Redux store获取当前用户角色
    const role = useSelector((s: RootState) => s.auth.role)
    //判断当前用户角色是否在允许角色列表中
    const allowed = role && allowRoles.includes(role)
    //如果当前用户角色不在允许角色列表中且deny为true，则隐藏按钮
    if (!allowed && deny) return null  // 隐藏按钮
    return (
        <button {...rest} disabled={!allowed || rest.disabled}>
            {children}
        </button>
    )
}


